package com.ittsang.config;

import com.ittsang.utils.LoginInterceptor;
import com.ittsang.utils.RefreshTokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/image/**").addResourceLocations("classpath:/image/");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // token刷新的拦截器
        registry.addInterceptor(new RefreshTokenInterceptor(stringRedisTemplate)).addPathPatterns("/**").order(0);

        // 登录拦截器
        registry.addInterceptor(new LoginInterceptor(stringRedisTemplate))
                .excludePathPatterns(
                        "/user/code",
                        "/user/register",
                        "/user/passwordLogin",
                        "/user/codeLogin",
                        "/**/getArticleTypeList",
                        "/article/getArticle",
                        "/article/getArticleByType",
                        "/article/getArticleInfoById",
                        "/article/search",
                        "/user/logout",
                        "/race/getRace",
                        "/article/getArticleInfoById",
                        "/comment/getCommentByArticle",
                        "/club/getAllClub",
                        "/club/getCLubDepByClubId",
                        "/race/getRaceType",
                        "/race/getRaceById",
                        "/user/managerLogin",
                        "/upload/image",
                        "/image/**"
                ).order(1);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
}
